package yunjiao.javatutorials.lang.concurrent;

import java.util.Arrays;
import java.util.Random;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveAction;

/**
 * 并行排序（RecursiveAction）
 *
 * @author yangyunjiao
 */
public class ParallelMergeSort  extends RecursiveAction {
    private static final int THRESHOLD = 1000;
    private final int[] array;
    private final int start;
    private final int end;

    public ParallelMergeSort(int[] array, int start, int end) {
        this.array = array;
        this.start = start;
        this.end = end;
    }

    @Override
    protected void compute() {
        if (end - start <= THRESHOLD) {
            // 小数组直接排序
            Arrays.sort(array, start, end);
        } else {
            int mid = (start + end) / 2;

            // 创建子任务
            ParallelMergeSort leftTask = new ParallelMergeSort(array, start, mid);
            ParallelMergeSort rightTask = new ParallelMergeSort(array, mid, end);

            // 并行执行
            invokeAll(leftTask, rightTask);

            // 合并结果
            merge(array, start, mid, end);
        }
    }

    private void merge(int[] array, int start, int mid, int end) {
        int[] temp = new int[end - start];
        int i = start, j = mid, k = 0;

        while (i < mid && j < end) {
            if (array[i] <= array[j]) {
                temp[k++] = array[i++];
            } else {
                temp[k++] = array[j++];
            }
        }

        while (i < mid) temp[k++] = array[i++];
        while (j < end) temp[k++] = array[j++];

        System.arraycopy(temp, 0, array, start, temp.length);
    }

    public static void main(String[] args) {
        int[] array = new int[100000];
        Random random = new Random();

        for (int i = 0; i < array.length; i++) {
            array[i] = random.nextInt(1000000);
        }

        ForkJoinPool pool = new ForkJoinPool();
        ParallelMergeSort task = new ParallelMergeSort(array, 0, array.length);

        long startTime = System.currentTimeMillis();
        pool.invoke(task);
        long endTime = System.currentTimeMillis();

        System.out.println("并行排序时间: " + (endTime - startTime) + "ms");

        // 验证排序结果
        for (int i = 1; i < array.length; i++) {
            if (array[i] < array[i-1]) {
                System.out.println("排序错误!");
                break;
            }
        }

        pool.shutdown();
    }
}
